/**
 * 
 */
package bi.uc.login;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.bi_uc.www.R;

import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.widget.EditText;


/**
 * @author Administrator
 * 
 */
public class Info {
	
	private static Info info;
	public boolean stopFlag; //是否连网
//	public String cardNum;	//卡号
	public Card card;
	public ArrayList<String> cardTypes; // 卡类名
	// ArrayList<String> cardLeves;
	public HashMap<String, ArrayList<String>> cardLeves; // 所有卡类对应的卡级别
	private ArrayList<String> singleLevels; // 单个卡类别对应的卡等级
	public String userID;			//操作员标识
	public String userName;			//操作员姓名
	public String employID;			//商家标识
	public String shopID;			//店面标识
	public HashMap<String, String> NameId; // 名称和标识键值对
	private String cardName = null; // 卡名称
	public double storeFactor;			//店面积分系数
	public double storeDiscount;		//店面折扣
	
	public boolean isPayNeedPassword;	//储值消费需要密码
	public boolean isStoreFactor;		//是否启用店面积分系数
	public boolean isStoreDiscount;		//是否启用店面折扣
	public boolean isGoodsFactor;		//是否启用商品积分系数
	public boolean isGoodsDiscount;		//是否启用商品折扣
	public boolean isChangeNeedPay;		//是否启用应付金额修改
	public boolean isCardQuickPay;			//快速消费是否启用会员卡支付
	public boolean isCashQuickPay;			//快速消费是否启用现金支付
	public boolean isCardPay;			//储值消费是否启用会员卡支付
	public boolean isCashPay;			//储值消费是否启用现金支付
	public ArrayList<HashMap<String, Object>> optionsList;	//功能模块选项
	/**
	 * 
	 */
	public Info() {
		super();
		// TODO Auto-generated constructor stub
		cardTypes = new ArrayList<String>();
		cardLeves = new HashMap<String, ArrayList<String>>();
		NameId = new HashMap<String, String>();
		optionsList = new ArrayList<HashMap<String, Object>>();
		card = new Card();
	}

	public static Info getInfo() {
		if (info == null) {
			info = new Info();
		}
		return info;
	}

	public void saveData(XmlPullParser parser, int eventType) throws Exception {
		userID = parser.getAttributeValue(null, "标识");
		userName = parser.getAttributeValue(null, "姓名");
		Log.d("userName", userName);
		employID = parser.getAttributeValue(null, "商家标识");
		shopID = parser.getAttributeValue(null, "店面标识");
		systemSet(parser.getAttributeValue(null, "系统设置"));
		systemSet(parser.getAttributeValue(null, "可用模块"));
/*		String string = parser.getAttributeValue(null, "可用模块");
		Log.d("系统设置", parser.getAttributeValue(null, "系统设置"));
		Log.d("可用模块", string.substring(0, string.length()/2));
		Log.d("可用模块", string.substring(string.length()/2, string.length()));*/
		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			// 文档开始
			case XmlPullParser.START_DOCUMENT:
				// 初始化
				// persons = new ArrayList<Person>();
				break;
			case XmlPullParser.START_TAG: // 开始标签
				if ("dbo.aCardType".equals(parser.getName())) {
					cardName = parser.getAttributeValue(null, "aCardType_名称");
					cardTypes.add(cardName);
					NameId.put(cardName,
							parser.getAttributeValue(null, "aCardType_Id"));
					singleLevels = new ArrayList<String>();
				}
				else if (cardName != null
						&& "dbo.aCardTypeLevel".equals(parser.getName())) {
					String cardLevel = parser.getAttributeValue(null,
							"aCardTypeLevel_名称");
					Log.d("cardLevel", cardLevel);
					singleLevels.add(cardLevel);
					NameId.put(cardLevel,
							parser.getAttributeValue(null, "aCardTypeLevel_Id"));
				}else if ("ITEM".equals(parser.getName()) && shopID.equals(parser.getAttributeValue(null, "店面标识")) ){
					storeFactor = Double.parseDouble(parser.getAttributeValue(null, "积分系数"));
					storeDiscount = Double.parseDouble(parser.getAttributeValue(null, "折扣系数"));
				}
				
				break;
			case XmlPullParser.TEXT:
				break;
			case XmlPullParser.END_TAG:// 结束标签
				Log.d("data", "END_TAG" + parser.getText());
				if ("dbo.aCardType".equals(parser.getName())) {
					cardLeves.put(cardName, singleLevels);
					cardName = null;// 再掷为null
					singleLevels = null;
				}
				break;
			default:
				break;
			}
			// 下一个节点
			eventType = parser.next();
		}
	}
	
	/**
	 * @param attributeValue
	 */
	private void systemSet(String str) throws Exception{
		// TODO Auto-generated method stub
		XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();    // 获取XmlPullParser的实例					
		XmlPullParser parser = pullParserFactory.newPullParser();	
		parser.setInput(new StringReader(str));		
		int eventType = parser.next();
		if (eventType == XmlPullParser.START_TAG){
			if (parser.getName().equals("Config")) {
				isPayNeedPassword = "是".equals(parser.getAttributeValue(null, "XiaoFeiNeedMiMa"));	//储值消费需要密码
				isStoreFactor = "是".equals(parser.getAttributeValue(null, "是否启用店面积分系数"));		//是否启用店面积分系数
				isStoreDiscount = "是".equals(parser.getAttributeValue(null, "是否启用店面折扣系数"));		//是否启用店面折扣
				isGoodsFactor = "是".equals(parser.getAttributeValue(null, "是否启用商品积分系数"));		//是否启用商品积分系数
				isGoodsDiscount = "是".equals(parser.getAttributeValue(null, "是否启用商品折扣系数"));		//是否启用商品折扣
				isChangeNeedPay = "是".equals(parser.getAttributeValue(null, "YingFuJinEKeYiXiuGai"));;		//是否启用应付金额修改
				String s = parser.getAttributeValue(null, "储值消费结账付款方式");
				isCardPay = s.indexOf("会员支付")<0?false:true;
				isCashPay = s.indexOf("现金支付")<0?false:true;
				s = parser.getAttributeValue(null, "快速结账付款方式");
				isCardQuickPay = s.indexOf("会员支付")<0?false:true;
				isCashQuickPay = s.indexOf("现金支付")<0?false:true;
			} else if(parser.getName().equals("Modules")) { 
				optionsList.clear();
				eventType = parser.next();
				while (eventType != XmlPullParser.END_DOCUMENT) {					
						if (eventType ==  XmlPullParser.START_TAG && "sModule".equals(parser.getName())) {
							if ("快速结账".equals(parser.getAttributeValue(null, "sModule_Key"))) {								
								HashMap<String, Object> map = new HashMap<String, Object>();
								map.put("image", R.drawable.quickpay);
								map.put("text", "快速结账");
								optionsList.add(map);
							} else if ("快速积分".equals(parser.getAttributeValue(null, "sModule_Key"))) {
								HashMap<String, Object> map = new HashMap<String, Object>();
								map.put("image", R.drawable.quickscroe);
								map.put("text", "快速积分");
								optionsList.add(map);
							} else if ("会员充值".equals(parser.getAttributeValue(null, "sModule_Key"))) {
								HashMap<String, Object> map = new HashMap<String, Object>();
								map.put("image", R.drawable.addmoney);
								map.put("text", "会员充值");
								optionsList.add(map);
							} else if ("储值消费".equals(parser.getAttributeValue(null, "sModule_Key"))) {
								HashMap<String, Object> map = new HashMap<String, Object>();
								map.put("image", R.drawable.pay);
								map.put("text", "储值消费");
								optionsList.add(map);
							} else if ("新建会员".equals(parser.getAttributeValue(null, "sModule_Key"))) {
								HashMap<String, Object> map = new HashMap<String, Object>();
								map.put("image", R.drawable.newmember);
								map.put("text", "新建会员");
								optionsList.add(map);
							}
						}						
						
					// 下一个节点
					eventType = parser.next();
				}
			}
		}
		
	}

	public void updata() throws Exception {
		String Url = "http://bi.bi-uc.com/BI.api";
		/*String Body = "Action=PDA-充值&商家=" + info.employID + "&店面="
				+ info.shopID + "&操作员=" + info.userID + "&卡号=" + cardNumString
				+ "&充值金额=" + moneyString;
		Log.d("data", Body);*/
		HttpPost httpRequest = new HttpPost(Url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair pair1 = new BasicNameValuePair("Action", "PDA-读卡");
		NameValuePair pair2 = new BasicNameValuePair("商家", info.employID);				
		NameValuePair pair3 = new BasicNameValuePair("卡号", info.card.cardNum);
		NameValuePair pair4 = new BasicNameValuePair("店面", info.shopID);
		params.add(pair1);
		params.add(pair2);
		params.add(pair3);
		params.add(pair4);
		HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
		httpRequest.setEntity(entity);
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(httpRequest);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			InputStream in = response.getEntity().getContent();// 接收服务器的数据
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();    // 获取XmlPullParser的实例					
			XmlPullParser parser = pullParserFactory.newPullParser();
			InputStreamReader responseReader = new InputStreamReader(in,"UTF-8");
			parser.setInput(responseReader);
			parser.next();
			int eventType = parser.getEventType();
			if (eventType == XmlPullParser.START_TAG&& parser.getName().equals("XML")) { 
				// String result = parser.getAttributeValue(0);
				String result = parser.getAttributeValue(null, "EXEC");
				if (result.equals("True")) {								
					info.card.score = Integer.parseInt(parser.getAttributeValue(null, "pCard_可用积分"));
					info.card.money = Double.parseDouble(parser.getAttributeValue(null, "pCard_可用储值"));
					info.card.cardType = parser.getAttributeValue(null, "aCardType_名称");
					info.card.cardLevel = parser.getAttributeValue(null, "aCardTypeLevel_名称");
					info.card.cardUser = parser.getAttributeValue(null, "pMember_姓名");
					StringBuffer sb = new StringBuffer(parser.getAttributeValue(null, "pMember_手机"));
					sb.replace(3, 7, "****");
					info.card.tel = sb.toString();
					info.card.isScorePay = "1".equals(parser.getAttributeValue(null, "aCardTypeLevel_是否启用积分抵现")); //是否启用积分抵现
					info.card.scoreMoneyExchange = Double.parseDouble(parser.getAttributeValue(null, "aCardTypeLevel_积分抵现系数")); //积分抵现系数
					info.card.scoreMoneyRatio = Double.parseDouble(parser.getAttributeValue(null, "aCardTypeLevel_积分抵现上限比例")); //积分抵现上限比例
					info.card.Factor = Double.parseDouble(parser.getAttributeValue(null, "aCardTypeLevel_积分系数"));		//会员卡积分系数
					info.card.Discount = Double.parseDouble(parser.getAttributeValue(null, "aCardTypeLevel_折扣系数"));		//会员卡折扣
					info.card.ruleArray = new JSONArray(parser.getAttributeValue(null, "aCardTypeLevel_会员日折扣积分规则"));
				} 
				else 
				{
					
					info.card.cardNum = null;
				}				
			}
			in.close();				
			responseReader.close();	
		}
		else
		{
			info.card.cardNum = null;
		}
	}
		
	public boolean isExist(String s){
		return null != s && !"".equals(s);
	}
	
	public String subZeroAndDot(String s) {
		if(s.indexOf(".") > 0){  
			s = s.replaceAll("0+?$|[.]0+?$", "");//去掉多余的0 
		}
		return s;
	}
	
	//编辑框输入光标保持在输入内容右边
	public void setSpan(EditText editText) {
		CharSequence text = editText.getText();
		// Debug.asserts(text instanceof Spannable);
		if (text instanceof Spannable) {
			Spannable spanText = (Spannable) text;
			Selection.setSelection(spanText, text.length());
		}
	}
	
	public class Card
	{
		public String cardNum;	//卡号
		public String cardType;	//卡类别
		public String cardLevel;	//卡级别
		public String cardUser;		//卡用户
		public String tel;			//会员手机号码
		
		public int score;	//可用积分
		public double money;	//可用储值
		public boolean isScorePay; //是否启用积分抵现
		public double scoreMoneyExchange; //积分抵现系数
		public double scoreMoneyRatio; //积分抵现上限比例
		public double Factor;			//会员卡积分系数
		public double Discount;		//会员卡折扣
		public JSONArray ruleArray;	//会员日折扣积分规则
	}
}